"""
read a matrix
return a esri ascii format
"""
# -*- coding: utf-8 -*-
import os
import pandas as pd


def format_esri_ascii(output_filepath, data, cell_size=1000, no_data_value=0):
    """format as esri ascii file"""
    data.to_csv(r'test.txt',
                sep='\t', index=False, header=False, float_format='%.3f')
    nrows, ncols = data.shape
    with open(output_filepath, 'w') as output_file:
        output_file.seek(0)
        output_file.write("NCOLS " + str(ncols) + "\n")
        output_file.write("NROWS " + str(nrows) + "\n")
        output_file.write("XLLCORNER 354644\n")
        output_file.write("YLLCORNER 365200\n")
        output_file.write("CELLSIZE " + str(cell_size) + "\n")
        output_file.write("NODATA_VALUE " + str(no_data_value) + "\n")
        input_file = open(r'test.txt', 'r')
        output_file.writelines(input_file.readlines())
        input_file.close()
        output_file.close()
    os.remove(r'test.txt')


def main():
    """main function"""
    dat_dir = r"F:/research/rainfall_estimation/dat/nimrod_output/2008/cum_rainfall"
    if not os.path.exists(dat_dir):
        os.makedirs(dat_dir)
    events = [1, 2, 3, 4, 5, 6, 7, 8]
    for e in events:
        input_filepath = os.path.join(dat_dir, "R" + str(e) + ".asc")
        output_filepath = os.path.join(dat_dir, "R" + str(e) + ".txt")
        input_dat = pd.read_csv(input_filepath, index_col=False, header=None)
        format_esri_ascii(output_filepath, input_dat)


if __name__ == '__main__':
    main()
